package com.hjj.concurrence.singleton;

/**
 * 双检查的DCL
 * 问题：创建对象分为三步
 * 1.分配内存空间
 * 2.初始化对象
 * 3.将内存空间的地址赋值给对应的引用
 * 2，3可能会重排序
 * @author hjj
 * @create 2019-12-16 10:20
 */
public class Singleton3 {
    private static Singleton3 singleton3;

    private Singleton3() {
    }

    public static synchronized Singleton3 getInstance() {
        if (singleton3 == null) {
            synchronized (Singleton3.class){
                if (singleton3 == null){
                    singleton3 = new Singleton3();
                }
            }
        }
        return singleton3;
    }

    public static void main(String[] args) {
        new Thread(() -> singleton3 = Singleton3.getInstance()).start();
        new Thread(() -> singleton3 = Singleton3.getInstance()).start();
        new Thread(() -> singleton3 = Singleton3.getInstance()).start();
        new Thread(() -> singleton3 = Singleton3.getInstance()).start();
//        System.out.println(singleton3.hashCode());
        Singleton3 s1 = Singleton3.getInstance();
        Singleton3 s2 = Singleton3.getInstance();
        Singleton3 s3 = Singleton3.getInstance();
        Singleton3 s4 = Singleton3.getInstance();
        Singleton3 s5 = Singleton3.getInstance();
        System.out.println(s1.hashCode());
        System.out.println(s2.hashCode());
        System.out.println(s3.hashCode());
        System.out.println(s4.hashCode());
        System.out.println(s5.hashCode());

    }
}
